<?php

namespace Cours\UserBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Session\Session;

class UtilisateurController extends Controller
{
    public function readUserAction(){
        /* Doctrine quand on getPromotion refait un requete -> add select permet de faire les deux en même temps -> gain d'une requete et donc de temps  */
        $groups = $this->getDoctrine()->getManager()
            ->createQueryBuilder()
            ->add('select', 'u')
            ->add('from', 'CoursUserBundle:User u')
            ->addSelect('p') // Pour info cela a réduit le nbr de requete de 6 à 2
            ->leftJoin("u.promotion","p")
            ->add('orderBy', 'p.libelle, u.username')
            ->getQuery()->getResult();

        $t=0;
        foreach ($groups as $u) {
        	$promo = $u->getPromotion();
        	if(!empty($promo)){
        		$t++;
        		$users[$u->getPromotion()->getCode()]["promo"]=ucwords($u->getPromotion()->getLibelle());
        		$users[$u->getPromotion()->getCode()]["promoid"]=$u->getPromotion()->getId();
        		$users[$u->getPromotion()->getCode()]["users"][$t]=$u;
        	}
        	unset($promo);
        }
        if($this->container->get('session')->has("selectedpromotion")){
            $promo=$this->container->get('session')->get("selectedpromotion");
            $array=array("users" =>$users,"promo"=>$promo);
        } else {
            $array=array("users" =>$users);
        }
     
        return $this->render('CoursUserBundle:Utilisateur:read.html.twig',$array);
    }

    public function delUserAction($id){
        $user = $this->container->get('fos_user.user_manager')->findUserBy(array("id"=>$id));

        $em=$this->getDoctrine()->getManager();
        $reponses = $em->getRepository('CoursQuizzBundle:Reponse')->findByIduser($user);
        foreach ($reponses as $reponse) {
            $em->remove($reponse);
            $em->flush();
        }

		$this->container->get('fos_user.user_manager')->deleteUser($user);
        
        $this->setFlash('fos_user_success', "L'Utilisateur à été supprimé avec succès !");

		return $this->redirect($this->generateUrl('readUser'));
    }

    public function setSessionAction(){
        if(isset($_POST['id'])){
            $session = $this->container->get('session');
            $session->set('selectedpromotion', $_POST['id']);
        }
        return $this->render('CoursQuizzBundle:Questions:blank.html.twig');
    }

    public function updateUserAction($id){

        $user = $this->container->get('fos_user.user_manager')->findUserBy(array("id"=>$id));
        
        $form = $this->container->get('fos_user.profile.form');
        $formHandler = $this->container->get('fos_user.profile.form.handler');

        $process = $formHandler->process($user);
        if ($process) {
            $this->setFlash('fos_user_success', 'profile.flash.updated');

        return $this->redirect($this->generateUrl('readUser'));
        }

        return $this->container->get('templating')->renderResponse(
            'FOSUserBundle:Profile:edit.html.'.$this->container->getParameter('fos_user.template.engine'),
            array('form' => $form->createView(),"id"=>$id,"user"=>$user)
        );
    }

    /**
     * @param string $action
     * @param string $value
     */
    protected function setFlash($action, $value)
    {
        $this->container->get('session')->getFlashBag()->set($action, $value);
    }

}
